package cx.zan.web.servlet;

import cx.zan.domain.Cart;
import cx.zan.domain.CartItem;
import cx.zan.domain.Product;
import cx.zan.service.ProductService;
import cx.zan.utils.RRHolder;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/4/1 14:46
 */
@WebServlet("/cart")
public class CartServlet extends BaseServlet {
    //创建productService对象
    private ProductService productService = new ProductService();

    //在一次会话中始终每个人 只有一个购物车
    private Cart getCart() {
        //获取sessiond对象
        HttpSession session = RRHolder.getRequest().getSession();
        //从session获取 数据
        Cart cart = (Cart) RRHolder.getRequest().getSession().getAttribute("x-cart");
        if (cart == null) {
            //第一次调用 第一次新建一个cart
            cart = new Cart();
            session.setAttribute("x-cart", cart);
        }
        return cart;
    }


    /**
     * 添加购物车 购物项
     * @param request
     * @param response
     * @throws IOException
     */
    public void addItem(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取参数
        //商品pid
        String pid = request.getParameter("pid");
        //商品数量
        int count = Integer.parseInt(request.getParameter("count"));

        //根据商品pid查询 商品数据
        Product product = productService.findById(pid);

        //购物项 购物车界面组装对象
        //封装cartItem对象
        CartItem cartItem = new CartItem();
        cartItem.setCount(count);
        cartItem.setProduct(product);

        //购物项应该放在购物车中
        Cart cart = getCart();

        cart.addItem(cartItem);
        //System.out.println(cart);
        writeSuccess("添加成功");
    }

    /**
     * 查看购物车中的所有商品
     * @param request
     * @param response
     * @throws IOException
     */
    public void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //取出自己的购物车中的商品信息 写出给浏览器
        Cart cart = getCart();

        System.out.println(cart);
        //返回给浏览器
        writeSuccess(cart);
    }

    /**
     * 清除购物车中的单个
     *
     * @param request
     * @param response
     * @throws IOException
     */
    protected void removeItem(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取要删除的购物项的pid
        String pid = request.getParameter("pid");
        getCart().removeItem(pid);
        writeSuccess("删除成功");
    }

    /**
     * 清空购物车
     *
     * @param request
     * @param response
     * @throws IOException
     */
    protected void clear(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cart cart = getCart();
        cart.clear();
        writeSuccess("清空完毕");
    }


}
